/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package formularios;

import Clases.AnchoColumna;
import Clases.AutoCompleteCombo;
import Clases.ComboBox;
import Clases.ModeloTabla;
import Clases.Tools;
import Clases.Transacciones;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Calendar;
import java.util.Date;
import java.util.Hashtable;
import java.util.Vector;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.text.JTextComponent;
import org.jdesktop.swingx.autocomplete.AutoCompleteDecorator;

/**
 *
 * @author Jrg
 */
public class CajaCobro extends javax.swing.JInternalFrame {

    public static int IdMenu=4;
    int _idAlumno, _idServicio;
    JTable _tabla;
    ModeloTabla _modeloTabla;
    double _totalSaldo, _totalAbono,_montoAbono;
    /**
     * Creates new form Caja de Cobro
     */
    public CajaCobro() 
    {
        initComponents();
        ObtenerFechaActual();
        CargarComboAlumno();
        CargarComboFormaPago();
        CargarComboBanco();
        AgregarListenerComboAlumno();
        AgregarListenerCombFormaPago();
        CrearModeloTabla();
        _idAlumno=0;
        panelCheque.setVisible(false);
    }
    
    private void ObtenerFechaActual()
    {
        jDateFecha.setDate(Transacciones.ObtenerFechaServidor(MainMenu.conexion));
    }
    
    private void CargarComboAlumno()
    {
        DefaultComboBoxModel modelo = Clases.ComboBox.CargarCombo("select idalumno id, nombre from alumnos where debaja is null order by nombre asc", MainMenu.conexion);
        cbAlumno.setModel(modelo);
        AutoCompleteDecorator.decorate(cbAlumno);
    }
    
    private void CargarComboBanco()
    {
        DefaultComboBoxModel modelo = Clases.ComboBox.CargarCombo("select idbanco id, nombre from bancos where debaja is null order by nombre asc", MainMenu.conexion);
        cbBanco.setModel(modelo);
        AutoCompleteDecorator.decorate(cbBanco);
    }
    
    private void CargarComboCliente()
    {
        DefaultComboBoxModel modelo = Clases.ComboBox.CargarCombo("SELECT e.identidad id, e.nombre  FROM alumnos a "+
                "inner join entidades e on a.idpadre=e.identidad where idalumno="+_idAlumno+
                " union SELECT e.identidad id, e.nombre  FROM alumnos a inner join entidades e on a.idmadre=e.identidad "+
                "where idalumno="+_idAlumno+" order by nombre asc", MainMenu.conexion);
        cbCliente.setModel(modelo);
        AutoCompleteDecorator.decorate(cbCliente);
    }
    
    private void CargarComboFormaPago()
    {
        DefaultComboBoxModel modelo = Clases.ComboBox.CargarCombo("select idformapago id, nombre from formapago where debaja is null order by idformapago asc", MainMenu.conexion);
        cbFormaPago.setModel(modelo);
        AutoCompleteDecorator.decorate(cbFormaPago);
        cbFormaPago.setSelectedIndex(0);
    }
    

    private void AgregarListenerComboAlumno()
    {
        cbAlumno.addActionListener (new ActionListener () 
        {
            public void actionPerformed(ActionEvent e) 
            {
                //LimpiarVariables();
                try
                {
                _idAlumno = ((ComboBox) cbAlumno.getSelectedItem()).getId();
                CargarComboCliente();
                cbCliente.setSelectedIndex(0);
                CargarCuotas();
                }
                catch(Exception ex) {}
            }
        });
        
        
//            cbAlumno.getEditor().getEditorComponent().addFocusListener( new FocusAdapter() {
//            @Override
//            public void focusGained( FocusEvent e ) {
//                if(e.getSource() instanceof JTextComponent) {
//                    ((JTextComponent)e.getSource()).setCaretPosition( 0 );
//                    ((JTextComponent)e.getSource()).selectAll();
//                }
//            }
//            @Override
//            public void focusLost( FocusEvent e ) {
//                if(e.getSource() instanceof JTextComponent) {
//                    ((JTextComponent)e.getSource()).setCaretPosition( 0 );
//                    ((JTextComponent)e.getSource()).selectAll();
//                   
//                }
//            }
//        } );
    }
    
    private void AgregarListenerCombFormaPago()
    {
        cbFormaPago.addActionListener (new ActionListener () 
        {
            public void actionPerformed(ActionEvent e) 
            {
                try
                {
                    ComboBox formapago = ((ComboBox) cbFormaPago.getSelectedItem());
                    if (formapago.getId()==1)
                        panelCheque.setVisible(false);
                    else
                        panelCheque.setVisible(true);
                }
                catch(Exception ex){}
            }
        });
        
        
   }
    
   
    private void CrearModeloTabla()
    {
        try
        {
            /*columnas que no son editables*/
            Hashtable colReadOnly= new Hashtable();
            colReadOnly.clear();
            colReadOnly.put(0, 0); //IdCuota
            colReadOnly.put(1, 100); //Vencimiento
            colReadOnly.put(2, 0); //IdServicio
            colReadOnly.put(3, 300); //Servicio
            colReadOnly.put(4, 200); //Saldo
            colReadOnly.put(5, 200); //Abono
            
            
            String[] columnNames = {"IdCuota","Vencimiento","IdServicio","Servicio","Saldo","Abono"};
            final Class<?>[] columnClasses = {Integer.class,Date.class, Integer.class, String.class, Double.class,Double.class}; 
            _modeloTabla = new ModeloTabla(colReadOnly)
            {
                @Override
                public Class<?> getColumnClass(int columnIndex)
                {
                    return columnClasses[columnIndex];
                }
            };
            _modeloTabla.setColumnIdentifiers(columnNames);
            _modeloTabla.RemoveAllRows();
            _tabla = new JTable(_modeloTabla);
            AnchoColumna ac = new AnchoColumna(_tabla,colReadOnly);
//          OcultarColumnas oc = new OcultarColumnas(_tabla,0);
            JScrollPane scroll = new JScrollPane(_tabla);
            _tabla.getTableHeader().setReorderingAllowed(false);
            panelTabla.setVisible(false);
            panelTabla.add(scroll);
            panelTabla.setVisible(true);
            panelTabla.repaint();
        }
        catch(Exception ex)
        {
            
        }
    }
    
    private void CargarCuotas()
    {
        try
        {
            _totalSaldo =0;
            _totalAbono =0;
            _modeloTabla.RemoveAllRows();
            ResultSet rs = MainMenu.conexion.EjecutarConsulta("select di.iddeinscripcion, di.vencimiento,a.idarticulo,a.nombre,di.saldo saldo,"+
                    "di.saldo Abono from detalleinscripcion di inner join articulos a on di.idarticulo=a.idarticulo inner join inscripciones i "+
                    "on di.idinscripcion=i.idinscripcion where i.idalumno="+_idAlumno+" and  i.debaja is null and di.debaja is null and di.saldo>0 "+
                    "order by di.vencimiento asc");
            while (rs.next())
            {
                Vector alumno = new Vector();
                alumno.addElement(rs.getInt("iddeinscripcion"));//0
                alumno.addElement(rs.getDate("vencimiento"));//1
                alumno.addElement(rs.getInt("idarticulo"));//2
                alumno.addElement(rs.getString("nombre"));//3
                alumno.addElement(rs.getDouble("saldo"));//4
                alumno.addElement(rs.getDouble("Abono"));//5
                _modeloTabla.addRow(alumno);
                _totalSaldo +=rs.getDouble("saldo");
                _totalAbono +=rs.getDouble("Abono");
            }
            
//            if (_totalAbono>_totalSaldo)
//            {
//                JOptionPane.showMessageDialog(this, "El Monto a abonar es mayor al saldo","Error",JOptionPane.ERROR_MESSAGE);
//                _totalAbono=_totalSaldo;
//            }
            tfMontoAbono.setText(String.valueOf(_totalAbono));
            tfTotalSaldo.setText(String.valueOf(_totalSaldo));
            tfTotalAbono.setText(String.valueOf(_totalAbono));
            tfNuevoSaldo.setText("0.00");
        }
        catch(Exception ex)
        {
            
        }
        finally
        {
            MainMenu.conexion.CerrarConexion();
        }
    }

    
    private void calcularabono()
    {
        _montoAbono=0;
        try
        {
            _montoAbono=(double)Math.round(Double.valueOf(tfMontoAbono.getText())*100)/100;
        }
        catch(Exception ex)
        {
            JOptionPane.showMessageDialog(this, "Debe Ingresar un monto valido","Error",JOptionPane.ERROR_MESSAGE);
            tfMontoAbono.setText("");
            tfMontoAbono.requestFocus();
        }
        if (_montoAbono>=0)
        {
            if (_montoAbono>_totalSaldo)
            {
                JOptionPane.showMessageDialog(this, "El Monto a abonar es mayor al saldo","Error",JOptionPane.ERROR_MESSAGE);
                _montoAbono=_totalSaldo;
                tfMontoAbono.setText(String.valueOf(_montoAbono));
                tfTotalSaldo.setText(String.valueOf(_totalSaldo));
                tfTotalAbono.setText(String.valueOf(_totalAbono));
                tfNuevoSaldo.setText("0.00");
            }
            else
            {
            
                tfTotalAbono.setText(String.valueOf(_montoAbono));
                tfNuevoSaldo.setText(String.valueOf(_totalSaldo-_montoAbono));
                for (int i = 0; i < _modeloTabla.getRowCount(); i++) 
                {
                    double saldoCuota = (double)_modeloTabla.getValueAt(i, 4);
                    if (_montoAbono>=saldoCuota)
                    {
                        _montoAbono-=saldoCuota;
                        _modeloTabla.setValueAt(saldoCuota, i, 5);
                    }
                    else
                    {
                        _modeloTabla.setValueAt(_montoAbono, i, 5);
                        _montoAbono=0;
                    }
                }
            }
           
        }
    }
    
    
    private void Guardar() throws SQLException
    {
        //crear un movinventario de tipo venta
        //rebajar el saldo de cada cuota abonada
        //crear partida
        
        int answer=JOptionPane.showConfirmDialog(null, "¿Desea procesar el pago?", "Confirme por favor", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
        if(answer == JOptionPane.YES_OPTION)
        {
            Connection _conexion=null;
            try
            {
                if (cbAlumno.getSelectedItem()!=null && cbCliente.getSelectedItem() !=null  && cbFormaPago.getSelectedItem() !=null)
                {
                    _montoAbono=0;
                    _montoAbono=(double)Math.round(Double.valueOf(tfMontoAbono.getText())*100)/100;
                    if (_montoAbono>0)
                    {
                        int idformapago =((ComboBox) cbFormaPago.getSelectedItem()).getId();
                        if (idformapago ==1 || (tfNoCheque.getText()!="" && cbBanco.getSelectedItem()!=null)) // si la forma de pago es efectivo o ingreso en no de cheque y banco
                        {
                            int idMov=0;
                            int idmovCuenta=0;
                            int idcliente =((ComboBox) cbCliente.getSelectedItem()).getId();
                            java.sql.Date fecha=Tools.ObtenerFechaSql(jDateFecha.getDate());
                            if (ValidarDetalle())
                            {
                                Class.forName("com.mysql.jdbc.Driver").newInstance();
                                _conexion = DriverManager.getConnection("jdbc:mysql://"+MainMenu.server+"/"+MainMenu.dataBase,MainMenu.user, MainMenu.password);
                                _conexion.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
                                _conexion.setAutoCommit(false);//Inicia la transaccion
                                Statement st = _conexion.createStatement();
                                if (idformapago ==1)
                                {
                                    st.execute("insert into movinventario(fecha,identidad,idformapago,idtipomov,idusuario,observaciones,norecibo) values('"+
                                        fecha+"',"+idcliente+","+idformapago+",1,"+MainMenu.IdUsuario+",'"+tfObservaciones.getText()+"','"+tfNumeroRecibo.getText()+"')",
                                        Statement.RETURN_GENERATED_KEYS);
                                }
                                else
                                {
                                    st.execute("insert into movinventario(fecha,identidad,idformapago,idtipomov,idusuario,observaciones,norecibo,nocheque,idbanco) values('"+
                                        fecha+"',"+idcliente+","+idformapago+",1,"+MainMenu.IdUsuario+",'"+tfObservaciones.getText()+"','"+tfNumeroRecibo.getText()+
                                            "','"+tfNoCheque.getText()+"',"+((ComboBox) cbFormaPago.getSelectedItem()).getId()+")",Statement.RETURN_GENERATED_KEYS);
                                }
                                ResultSet rs = st.getGeneratedKeys();
                                if(rs.next()) 
                                    idMov = rs.getInt(1);
                                for (int i = 0; i < _modeloTabla.getRowCount(); i++) 
                                {
                                    if ((double)_modeloTabla.getValueAt(i, 5)>0)
                                    {
                                        PreparedStatement pst = _conexion.prepareStatement("insert into detallemovinventario (idmov,idarticulo,cantidad,precio) VALUES (?,?,?,?)");
                                        pst.setInt(1, idMov);
                                        pst.setInt(2, (int)_modeloTabla.getValueAt(i, 2));
                                        pst.setDouble(3, 1);
                                        pst.setDouble(4, (double)_modeloTabla.getValueAt(i, 5));
                                        pst.execute();
                                        double nuevoSaldo=(double)_modeloTabla.getValueAt(i, 4) - (double)_modeloTabla.getValueAt(i, 5);
                                        st.executeUpdate("update detalleinscripcion set saldo="+nuevoSaldo+" where iddeinscripcion="+(int)_modeloTabla.getValueAt(i, 0));
                                    }
                                }
                                /*inserta el movimiento de cuenta */
                                Statement stMovCuenta = _conexion.createStatement();
                                stMovCuenta.execute("insert into movcuenta(fecha,tipo,id,idusuario,observaciones) values('"+Tools.ObtenerFechaSql(jDateFecha.getDate())+"',1,"+idMov+","+MainMenu.IdUsuario+",'Abono')",Statement.RETURN_GENERATED_KEYS);
                                ResultSet rsMovCuenta = stMovCuenta.getGeneratedKeys();
                                if(rsMovCuenta.next()) 
                                    idmovCuenta = rsMovCuenta.getInt(1);
                                stMovCuenta.execute("insert into detallemovcuenta(idmovcuenta,idcuenta,debe,haber) values("+idmovCuenta+",8,"+0+","+_montoAbono+")");
                                stMovCuenta.execute("insert into detallemovcuenta(idmovcuenta,idcuenta,debe,haber) values("+idmovCuenta+",4,"+_montoAbono+","+0+")");
                                /*actualiza el saldo de la cuenta */
                                /*aunmenta el saldo de la cuenta CAJA */
                                st.execute("update cuentas set saldo = saldo + "+_montoAbono+" where idcuenta = 4");
                                /*reduce el saldo de la cuenta CUENTAS POR COBRAR */
                                st.execute("update cuentas set saldo = saldo - "+_montoAbono+" where idcuenta = 8");
                                _conexion.commit();
                                JOptionPane.showMessageDialog(this, "Los datos se almacenaron correctamente","Información",JOptionPane.INFORMATION_MESSAGE);
                                LimpiarVariables();
                            }
                            else
                                JOptionPane.showMessageDialog(this, "Debe agregar almenos un detalle al cobro","Error",JOptionPane.ERROR_MESSAGE);
                        }
                        else
                            JOptionPane.showMessageDialog(this, "Debe ingresar el No. de Cheque y seleccionar el Banco","Error",JOptionPane.ERROR_MESSAGE);
                        
                    }
                    else
                        JOptionPane.showMessageDialog(this, "El Monto a Abonar debe ser mayor a cero","Error",JOptionPane.ERROR_MESSAGE);
                }
                else
                    JOptionPane.showMessageDialog(this, "Debe seleccionar un alumno, forma de pago \n  y a nombre de quien saldra el recibo","Error",JOptionPane.ERROR_MESSAGE);
            }
            catch(Exception ex)
            {
                if (_conexion != null) 
                    _conexion.rollback();
                JOptionPane.showMessageDialog(this, ex,"Error",JOptionPane.ERROR_MESSAGE);
            }
            finally
            {
                if (_conexion != null && !_conexion.isClosed())
                {
                    _conexion.close();
                    _conexion=null;
                    System.gc();
                }
            }
        }
        
    }
    
    private boolean ValidarDetalle()
    {
        if (_modeloTabla.getRowCount()>0)
            return true;
        return false;
    }
    
    private void LimpiarVariables()
    {
        ObtenerFechaActual();
        CargarComboFormaPago();
        CargarComboAlumno();
        CargarComboCliente();
        _idAlumno=0;
        _totalSaldo =0;
        _totalAbono =0;
        _montoAbono =0;
        tfMontoAbono.setText("0.00");
        tfTotalSaldo.setText("0.00");
        tfTotalAbono.setText("0.00");
        tfNuevoSaldo.setText("0.00");
        _modeloTabla.RemoveAllRows();
        panelCheque.setVisible(false);
    }
    
    private void Nuevo()
    {
        int answer=JOptionPane.showConfirmDialog(null, "Perdera los datos no guardados, \n ¿desea continuar?", "Confirme por favor", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
        if(answer == JOptionPane.YES_OPTION)
        {
            LimpiarVariables();
        }
    }
    
    private void AddBanco()
    {
        QuickAddBanco d = new QuickAddBanco(null, true,"",0);
        d.setVisible(true);  
        if (d._id!=0 && d._nombre!="")
        {
            CargarComboBanco();
            ComboBox grado = new ComboBox(d._id,d._nombre);
            cbBanco.getModel().setSelectedItem(grado);
        }
        d.dispose();
        System.gc();
    }
    
    private void EditarBanco()
    {
        ComboBox grado = ((ComboBox) cbBanco.getSelectedItem());
        QuickAddBanco d = new QuickAddBanco(null, true,grado.getNombre(),grado.getId());
        d.setVisible(true);  
        if (d._id!=0 && d._nombre!="")
        {
            CargarComboBanco();
            ComboBox gradoNew = new ComboBox(d._id,d._nombre);
            cbBanco.getModel().setSelectedItem(gradoNew);
        }
        d.dispose();
        System.gc();
    }
    
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        panelEncabezado = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        cbCliente = new javax.swing.JComboBox();
        cbAlumno = new javax.swing.JComboBox();
        tfNumeroRecibo = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jDateFecha = new com.toedter.calendar.JDateChooser();
        cbFormaPago = new javax.swing.JComboBox();
        panelCheque = new javax.swing.JPanel();
        jLabel7 = new javax.swing.JLabel();
        tfNoCheque = new javax.swing.JTextField();
        jLabel8 = new javax.swing.JLabel();
        cbBanco = new javax.swing.JComboBox();
        btnAddGrado = new javax.swing.JButton();
        btnAddGrado1 = new javax.swing.JButton();
        panelPie = new javax.swing.JPanel();
        jLabel5 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tfObservaciones = new javax.swing.JTextArea();
        jPanel1 = new javax.swing.JPanel();
        btnNuevo = new javax.swing.JButton();
        btnGuardar = new javax.swing.JButton();
        jPanel4 = new javax.swing.JPanel();
        jLabel9 = new javax.swing.JLabel();
        tfTotalSaldo = new javax.swing.JTextField();
        jLabel10 = new javax.swing.JLabel();
        tfTotalAbono = new javax.swing.JTextField();
        jLabel12 = new javax.swing.JLabel();
        tfNuevoSaldo = new javax.swing.JTextField();
        panelTabla = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        jLabel11 = new javax.swing.JLabel();
        tfMontoAbono = new javax.swing.JTextField();

        setClosable(true);
        setMaximizable(true);
        setResizable(true);
        setTitle("Caja de Cobro");
        setToolTipText("");

        jLabel1.setText("Fecha");

        tfNumeroRecibo.setHorizontalAlignment(javax.swing.JTextField.RIGHT);

        jLabel4.setText("Alumno");

        jLabel6.setText("No Recibo");

        jLabel3.setText("A Nombre de");

        jLabel2.setText("Forma de Pago");

        jDateFecha.setEnabled(false);

        panelCheque.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel7.setText("No. Cheque");

        tfNoCheque.setHorizontalAlignment(javax.swing.JTextField.RIGHT);

        jLabel8.setText("Banco");

        btnAddGrado.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/add24.png"))); // NOI18N
        btnAddGrado.setToolTipText("Nuevo");
        btnAddGrado.setBorder(javax.swing.BorderFactory.createCompoundBorder());
        btnAddGrado.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddGradoActionPerformed(evt);
            }
        });

        btnAddGrado1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/edit24.png"))); // NOI18N
        btnAddGrado1.setToolTipText("Editar");
        btnAddGrado1.setBorder(javax.swing.BorderFactory.createCompoundBorder());
        btnAddGrado1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddGrado1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout panelChequeLayout = new javax.swing.GroupLayout(panelCheque);
        panelCheque.setLayout(panelChequeLayout);
        panelChequeLayout.setHorizontalGroup(
            panelChequeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelChequeLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panelChequeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel7)
                    .addComponent(jLabel8))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(panelChequeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(tfNoCheque)
                    .addComponent(cbBanco, 0, 149, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnAddGrado)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnAddGrado1)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        panelChequeLayout.setVerticalGroup(
            panelChequeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelChequeLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panelChequeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(btnAddGrado1, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnAddGrado, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(panelChequeLayout.createSequentialGroup()
                        .addGroup(panelChequeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel7)
                            .addComponent(tfNoCheque, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(panelChequeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel8)
                            .addComponent(cbBanco, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout panelEncabezadoLayout = new javax.swing.GroupLayout(panelEncabezado);
        panelEncabezado.setLayout(panelEncabezadoLayout);
        panelEncabezadoLayout.setHorizontalGroup(
            panelEncabezadoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelEncabezadoLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panelEncabezadoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel6)
                    .addComponent(jLabel4)
                    .addComponent(jLabel3))
                .addGap(18, 18, 18)
                .addGroup(panelEncabezadoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(panelEncabezadoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(tfNumeroRecibo)
                        .addComponent(cbCliente, 0, 281, Short.MAX_VALUE))
                    .addComponent(cbAlumno, javax.swing.GroupLayout.PREFERRED_SIZE, 281, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(34, 34, 34)
                .addGroup(panelEncabezadoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(panelEncabezadoLayout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(71, 71, 71)
                        .addComponent(jDateFecha, javax.swing.GroupLayout.PREFERRED_SIZE, 158, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(panelEncabezadoLayout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(cbFormaPago, javax.swing.GroupLayout.PREFERRED_SIZE, 158, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(18, 18, 18)
                .addComponent(panelCheque, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        panelEncabezadoLayout.setVerticalGroup(
            panelEncabezadoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelEncabezadoLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panelEncabezadoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(panelEncabezadoLayout.createSequentialGroup()
                        .addGroup(panelEncabezadoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(panelEncabezadoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jLabel4)
                                .addComponent(cbAlumno, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jLabel1))
                            .addComponent(jDateFecha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(panelEncabezadoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(tfNumeroRecibo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel6)
                            .addComponent(jLabel2)
                            .addComponent(cbFormaPago, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(panelEncabezadoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(cbCliente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel3)))
                    .addComponent(panelCheque, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jLabel5.setText("Observaciones");

        tfObservaciones.setColumns(20);
        tfObservaciones.setRows(5);
        jScrollPane1.setViewportView(tfObservaciones);

        btnNuevo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/add24.png"))); // NOI18N
        btnNuevo.setText("Nuevo");
        btnNuevo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNuevoActionPerformed(evt);
            }
        });

        btnGuardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/floppy24.png"))); // NOI18N
        btnGuardar.setText("Guardar");
        btnGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGuardarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(btnNuevo, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btnGuardar, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 166, Short.MAX_VALUE))
                .addContainerGap(21, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(btnNuevo)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnGuardar)
                .addContainerGap(50, Short.MAX_VALUE))
        );

        jLabel9.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        jLabel9.setText("Saldo Total");

        tfTotalSaldo.setEditable(false);
        tfTotalSaldo.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        tfTotalSaldo.setHorizontalAlignment(javax.swing.JTextField.RIGHT);

        jLabel10.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        jLabel10.setText("Total Abono");

        tfTotalAbono.setEditable(false);
        tfTotalAbono.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        tfTotalAbono.setHorizontalAlignment(javax.swing.JTextField.RIGHT);

        jLabel12.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        jLabel12.setText("Nuevo Saldo");

        tfNuevoSaldo.setEditable(false);
        tfNuevoSaldo.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        tfNuevoSaldo.setHorizontalAlignment(javax.swing.JTextField.RIGHT);

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel4Layout.createSequentialGroup()
                        .addComponent(jLabel12)
                        .addGap(18, 18, 18)
                        .addComponent(tfNuevoSaldo, javax.swing.GroupLayout.PREFERRED_SIZE, 136, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel4Layout.createSequentialGroup()
                        .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel10)
                            .addComponent(jLabel9))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(tfTotalSaldo, javax.swing.GroupLayout.PREFERRED_SIZE, 138, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(tfTotalAbono, javax.swing.GroupLayout.PREFERRED_SIZE, 138, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(92, Short.MAX_VALUE))
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addGap(13, 13, 13)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel9)
                    .addComponent(tfTotalSaldo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel10)
                    .addComponent(tfTotalAbono, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel12)
                    .addComponent(tfNuevoSaldo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout panelPieLayout = new javax.swing.GroupLayout(panelPie);
        panelPie.setLayout(panelPieLayout);
        panelPieLayout.setHorizontalGroup(
            panelPieLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelPieLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panelPieLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel5)
                    .addGroup(panelPieLayout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 307, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(127, 127, 127)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        panelPieLayout.setVerticalGroup(
            panelPieLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelPieLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panelPieLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(panelPieLayout.createSequentialGroup()
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(panelPieLayout.createSequentialGroup()
                        .addComponent(jLabel5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(panelPieLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jScrollPane1)))))
        );

        panelTabla.setLayout(new java.awt.CardLayout());

        jLabel11.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        jLabel11.setText("Monto a abonar");

        tfMontoAbono.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        tfMontoAbono.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        tfMontoAbono.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                CalcularAbono(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel11)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(tfMontoAbono, javax.swing.GroupLayout.PREFERRED_SIZE, 146, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel11)
                    .addComponent(tfMontoAbono, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(panelEncabezado, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(panelPie, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(panelTabla, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(panelEncabezado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(panelTabla, javax.swing.GroupLayout.DEFAULT_SIZE, 160, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(panelPie, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnNuevoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNuevoActionPerformed
       Nuevo();
    }//GEN-LAST:event_btnNuevoActionPerformed

    private void btnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGuardarActionPerformed
        try
        {
            Guardar();
        }
        catch(Exception ex)
        {
            JOptionPane.showMessageDialog(this, ex,"Error",JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_btnGuardarActionPerformed

    private void CalcularAbono(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_CalcularAbono
        calcularabono();
    }//GEN-LAST:event_CalcularAbono

    private void btnAddGradoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddGradoActionPerformed
         AddBanco();
    }//GEN-LAST:event_btnAddGradoActionPerformed

    private void btnAddGrado1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddGrado1ActionPerformed
         EditarBanco();
    }//GEN-LAST:event_btnAddGrado1ActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAddGrado;
    private javax.swing.JButton btnAddGrado1;
    private javax.swing.JButton btnGuardar;
    private javax.swing.JButton btnNuevo;
    private javax.swing.JComboBox cbAlumno;
    private javax.swing.JComboBox cbBanco;
    private javax.swing.JComboBox cbCliente;
    private javax.swing.JComboBox cbFormaPago;
    private com.toedter.calendar.JDateChooser jDateFecha;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JPanel panelCheque;
    private javax.swing.JPanel panelEncabezado;
    private javax.swing.JPanel panelPie;
    private javax.swing.JPanel panelTabla;
    private javax.swing.JTextField tfMontoAbono;
    private javax.swing.JTextField tfNoCheque;
    private javax.swing.JTextField tfNuevoSaldo;
    private javax.swing.JTextField tfNumeroRecibo;
    private javax.swing.JTextArea tfObservaciones;
    private javax.swing.JTextField tfTotalAbono;
    private javax.swing.JTextField tfTotalSaldo;
    // End of variables declaration//GEN-END:variables
}
